package com.ydj.framework.module.proxy;

import com.ydj.framework.exception.CommonException;
import com.ydj.framework.filter.ExtHttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class ProxyUrlService {
    /**
     * 代理URL
     */
    public void proxy(String url, ExtHttpServletResponse response) throws CommonException {
        response.setOutputFileFlag(true);
        ServletOutputStream outputStream = response.getOutputStream();

        String decodeUrl = UriUtils.decode(url, StandardCharsets.UTF_8);
        try {
            // 先进行下载
            OkHttpClient okHttpClient = new OkHttpClient();
            Request downloadRequest = new Request.Builder()
                    .get()
                    .url(decodeUrl)
                    .build();
            Response downloadResponse = okHttpClient.newCall(downloadRequest).execute();
            response.setContentType(downloadResponse.header("content-type"));
            outputStream.write(downloadResponse.body().bytes());
        } catch (Exception e) {
            log.error("代理URL下载失败,url=" + url, e);
            response.setStatus(404);
        }
    }
}
